/**
 * 
 */
package it.unitn.testbed.server.task;

import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;

/**
 * This servlet handles the submission of new images to be flashed on motes as
 * part of a task.
 * 
 * @author Stefan Guna
 * 
 */
public class TaskUpload extends UploadAction {
	public static Logger log = Logger.getLogger(TaskUpload.class.getName());

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/*
	 * (non-Javadoc)
	 * 
	 * @seegwtupload.server.UploadAction#executeAction(javax.servlet.http.
	 * HttpServletRequest, java.util.List)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String executeAction(HttpServletRequest request,
			List<FileItem> sessionFiles) throws UploadActionException {
		byte[] fileContents = null;
		String fileName = null;
		ArrayList<Integer> motes = new ArrayList<Integer>();
		log.trace("Uploading task");

		for (FileItem item : sessionFiles) {
			if (item.isFormField()) {
				int moteId;
				try {
					moteId = Integer.parseInt(item.getFieldName());
				} catch (NumberFormatException e) {
					continue;
				}
				motes.add(moteId);
			} else {
				fileName = item.getName();
				fileContents = item.get();
			}
		}
		removeSessionFileItems(request);

		if (fileName == null || fileContents == null)
			return "Unable to obtain images contents";

		HttpSession session = request.getSession(true);
		synchronized (session) {
			ArrayList<TaskComponent> taskComponents = (ArrayList<TaskComponent>) session
					.getAttribute("taskComponents");
			if (taskComponents == null) {
				taskComponents = new ArrayList<TaskComponent>();
				session.setAttribute("taskComponents", taskComponents);
			}
			taskComponents
					.add(new TaskComponent(motes, fileName, fileContents));
		}
		return "Image uploaded successfuly";
	}

}
